package com.github.m6d21.conflict.util;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.function.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文件相关工具类
 */
public class FileUtil {

    private final static Logger LOG = LoggerFactory.getLogger(FileUtil.class);

    public final static String PROPERTIES_TYPE = ".properties";

    /**
     *获取工程路径
     *
     * @author liuyang
     * @date 2018-12-05 Wed 11:30:38
     * return 工程路径
     */
    public static String getProjectPath() {
        File directory = new File("");// 参数为空
        String canonicalPath = null;
        try {
            canonicalPath = directory.getCanonicalPath();
        } catch (IOException e) {
            LOG.error("获取工程路径时发生异常,", e);
        }
        return canonicalPath;
    }

    /**
     *获取工程Module对应路径
     *
     * @author liuyang
     * @date 2018-12-05 Wed 11:27:34
     * return
     */
    public static String getProjectModulePath() {
        String classPath = "";
        try {
            classPath = Thread.currentThread().getContextClassLoader().getResource(".").getPath();
        } catch (Exception e) {
            LOG.error("获取classpath异常：{}", e);
        }
        //class文件的绝对路径分割成目录
        Iterator<String> pathIterator = Splitter.on(File.separatorChar).split(classPath).iterator();
        List<String> list = Lists.newArrayList(pathIterator);

        //项目module路径深度（编译后一般是 项目module路径+/target/classes+类文件相对路径）
        //需要去除末尾（target、classes、/）
        int validLen = list.size() - 3;
        List<String> dir = new ArrayList<>();
        for (int i = 0; i < validLen; i++) {
            dir.add(list.get(i));
        }
        return Joiner.on(File.separator).join(dir);
    }

    /**
     * 获取classpath路径
     */
    public static String getClasspath() {
        String classPath = "";
        try {
            classPath = Thread.currentThread().getContextClassLoader().getResource(".").getPath();
        } catch (Exception e) {
            LOG.error("获取classpath异常：{}", e);
        }
        return classPath;
    }

    @SuppressWarnings("all")
    public static byte[] loadFile2Bytes(String path) throws IOException {
        return loadFile2Bytes(new FileInputStream(new File(path)));
    }

    @SuppressWarnings("all")
    public static byte[] loadFile2Bytes(InputStream is) throws IOException {
        byte[] bytes = null;
        try {
            bytes = new byte[is.available()];
            is.read(bytes);
        } finally {
            CloseUtil.close(is);
        }
        return bytes;
    }

    /**
     * 合并Properties
     * @param multiProperties 多个Properties
     */
    public static Properties mergeProperties(Properties... multiProperties) {
        Properties merge = new Properties();
        if (multiProperties == null) {
            return merge;
        }

        for (Properties properties : multiProperties) {
            if (properties == null) {
                continue;
            }
            for (Map.Entry entry : properties.entrySet()) {
                merge.put(entry.getKey(), entry.getValue());
            }
        }
        return merge;
    }

    /**
     * 读取properties文件
     * @param path 文件路径
     */
    public static Properties readReadProperties(String path) {
        if (StringUtils.isBlank(path) || !path.endsWith(PROPERTIES_TYPE)) {
            throw new UnsupportedOperationException("不支持非properties文件类型");
        }
        InputStream is = null;
        Properties properties = null;
        try {
            is = new FileInputStream(new File(path));
            properties = new Properties();
            properties.load(is);
        } catch (IOException e) {
            LOG.error("读取文件[{}]失败: {}", path, e);
        } finally {
            CloseUtil.close(is);
        }
        return properties;
    }

    /**
     * 非递归遍历指定文件
     */
    public static Set<File> findFiles(String path, Predicate<File> predicate) {
        File root = new File(path);

        if (!exists(root) || predicate == null) {
            return new HashSet<>();
        }
        //保存目标文件及目录
        Set<File> foundSet = new HashSet<>(128);

        LinkedList<File> list = new LinkedList<File>();

        File[] files = listFiles(root);

        for (File f : files) {
            if (f.isDirectory()) {
                //目录需要放到LIST中继续遍历
                list.add(f);
            }
            if (predicate.test(f)) {
                foundSet.add(f);
            }
        }

        File temp;
        while (!list.isEmpty()) {
            temp = list.removeFirst();
            files = listFiles(temp);
            for (File f : files) {
                if (f.isDirectory()) {
                    list.add(f);
                }
                if (predicate.test(f)) {
                    foundSet.add(f);
                }
            }
        }
        return foundSet;
    }

    /**
     * 读取文件文件
     */
    public static String readTextFile(String path) {
        if (StringUtils.isEmpty(path)) {
            return "";
        }

        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        StringBuilder sb = new StringBuilder();
        try {
            fileReader = new FileReader(path);
            bufferedReader = new BufferedReader(fileReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (IOException e) {
            LOG.error("读取文件失败：{}，error:{}", path, e);
        } finally {
            CloseUtil.close(bufferedReader);
            CloseUtil.close(fileReader);
        }
        return sb.toString();
    }

    public static String readTextFile(InputStream inputStream) {
        if (inputStream == null) {
            return "";
        }

        String text = "";
        try {
            int len = inputStream.available();
            byte[] bytes = new byte[len];
            inputStream.read(bytes);
            text = new String(bytes);
        } catch (IOException e) {
            LOG.error("读取输入流失败，error:{}", e);
        }
        return text;
    }

    public static File[] listFiles(File file) {
        if (file == null) {
            return new File[0];
        }
        File[] files = file.listFiles();
        if (files == null) {
            files = new File[0];
        }
        return files;
    }

    public static boolean exists(File file) {
        if (file != null && file.exists()) {
            return true;
        }
        return false;
    }

}
